package com.rykj.base

import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.rykj.R
import com.rykj.util.C
import com.rykj.widget.TopBar
import com.rykj.widget.TopBar.onTopBarClickListener
import com.rykj.widget.WebViewCommon

class WebViewActivity : BaseActivity(), onTopBarClickListener {
    var topbar: TopBar? = null
    var webcommon: WebViewCommon? = null


    private var url = ""
    private var title = ""

    override fun onCreate(bundle: Bundle?) {
        initData()
        super.onCreate(bundle)
    }

    override fun onDestroy() {
        super.onDestroy()
        webcommon!!.destroy()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_webview;
    }

    override fun onTopBarViewClick(v: View) {
        val id = v.id
        if (id == R.id.topBarImgBtnLeft) {
            val webview = webcommon!!.webview
            if (webview.canGoBack()) {
                webview.goBack()
            } else {
                super.onBackPressed()
            }
        } else if (id == R.id.topBarTvRight) {
        }
    }

    override fun onBackPressed() {
        val webview = webcommon!!.webview
        if (webview.canGoBack()) {
            webview.goBack()
        } else {
            super.onBackPressed()
        }
    }

    private fun initData() {
        url = intent.getStringExtra(C.IntentKey.URL)
        title = intent.getStringExtra(C.IntentKey.TITLE)
    }

    override fun initView(bundle: Bundle?) {
        topbar = findViewById(R.id.topbar)
        webcommon = findViewById(R.id.webcommon)

        topbar!!.setTitleText(title).setLeftImgEnable(true).setTopBarClickListener(this)
        if (url.startsWith("http")) {
            webcommon!!.loadUrl(url)
        } else {
            webcommon!!.loadData(url)
        }
    }

    companion object {
        /**
         * 启动 WebViewActivity
         * @param url
         * web 链接地址   或  Html 字符串
         */
        fun start(application: Context, url: String?, title: String?) {
            val intent = Intent(application, WebViewActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.putExtra(C.IntentKey.URL, url)
            intent.putExtra(C.IntentKey.TITLE, title)
            application.startActivity(intent)
        }
    }
}